<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax请求</title>
  <style>
    #jg {
      width: 400px;
      height: 300px;
      padding: 5px 10px;
      border: 1px solid orange;
    }
    h2{
      text-align: center;
    }
    p{
      font-size: 23px;
      font-family: '楷体';
      font-weight: bold;
      text-align: center;
    }
  </style>
</head>

<body>
  <div class="wrap">
    <button id="btn">一句名言</button><br><br>
    <div id="jg">

    </div>
  </div>
</body>
<script>
  // 接口：https://api.apiopen.top/api/sentences
  window.onload = function () {
    const btn = document.getElementById('btn');
    const jg = document.getElementById('jg');

    btn.onclick = function () {
      const p = new Promise((resolve, resjct) => {
        const xhr = new XMLHttpRequest()
        xhr.responseType = "json"
        xhr.open('GET', 'https://api.apiopen.top/api/sentences');
        xhr.send()
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              resolve(xhr.response);
            } else {
              resjct(xhr.status);
            }
          }
        }
      })

      p.then((value) => {
        const h2 = document.createElement('h2');
        h2.innerHTML = value.result.from
        jg.appendChild(h2)
        const p = document.createElement('p')
        p.innerHTML = value.result.name
        jg.appendChild(p)
        console.log(value.result);
      }, (reason) => {
        console.warn(reason);
      })
    }
  }
</script>

</html>